package org.agile4j.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 多线程中有用时间记录器
 * 
 * @author hanyx
 */
public class TimeHolder {

	private static ThreadLocal<Map<String,Long>> timeContainer = new ThreadLocal<Map<String,Long>>() {
		@Override
		protected Map<String, Long> initialValue() {
			Map<String, Long> map = new HashMap<>();
			return map;
		}
	} ;
	
	public static Map<String, Long> get(){
		return timeContainer.get() ;
	}
	
	public static void put(Map<String, Long> map) {
		timeContainer.set(map);
	}
	
	public static void clear(){
		timeContainer.set(null);
	}
	
	public static void addTime(String key, Long time) {
		Long t = get().get(key) ;
		if (t == null) {
			t = 0L ;
		}
		t = t + time ;
		get().put(key, t) ;
	}
	
	public static void main(String[] args) throws Exception {
		// 第一次 记录
		Long t1 = System.currentTimeMillis() ;
		TimeUnit.SECONDS.sleep(4);
		Long r1 = System.currentTimeMillis() - t1 ; // 耗时4秒 4000
		TimeHolder.addTime("hanyx", r1);
		System. out.println(TimeHolder.get().get("hanyx"));
		
		// 无用耗时
        TimeUnit.SECONDS.sleep(2);
        
        // 第二次耗时
        t1 = System.currentTimeMillis() ;
        TimeUnit.SECONDS.sleep(3);
        r1 = System.currentTimeMillis() - t1 ;
        TimeHolder.addTime("hanyx", r1);
        System.out.println(TimeHolder.get().get("hanyx"));// 耗时7秒
	}
}
